package com.atjava.webspider.util;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.atjava.jox.JOXManager;


/**
 * Java反射工具类
 * @author kyo
 */
public class ReflectUtil {

	/**
	 * 获取集合类成员变量泛型
	 * @param cls
	 * @param name
	 * @return Class
	 * @throws Exception
	 */
	public static Class<?> getFieldGenericType(Class<?> cls,String name)throws Exception{
		
		Method getMethod = cls.getMethod
		("get" + JOXManager.fstCharUpperCase(name));
		
		ParameterizedType pt = (ParameterizedType)getMethod.getGenericReturnType();
		Type [] types = pt.getActualTypeArguments();
		if(types == null || types.length == 0)
			throw new Exception
			("the field [ " + name + " ] of the class [ " + cls.getName() + " ] must be generic type");
		
		return (Class<?>)types[0];
	}
	
	/**
	 * 获取非集合类成员变量的类型
	 * @param cls
	 * @param name
	 * @return Class
	 * @throws BusinessException
	 */
	public static Class<?> getFieldType(Class<?> cls,String name)throws Exception{
		Method getMethod = null;
		try {
			getMethod = cls.getMethod
			("get" + JOXManager.fstCharUpperCase(name));
		} catch (Exception e) {
			return null;
		}
		return getMethod.getReturnType();
	}
	
	/**
	 * 设置指定对象上的指定属性的值
	 * @param obj
	 * @param propName
	 * @param value
	 * @throws BusinessException
	 */
	public static void setValue(Object obj,String propName,Object value)throws Exception{
		try {
			//获得SET方法参数类型
			Class<?> typeCls = getFieldType(obj.getClass(),propName);
			Method setMethod = obj.getClass().getMethod
			("set" + JOXManager.fstCharUpperCase(propName), typeCls);
			setMethod.invoke(obj, value);
		} catch (Exception e) {
			throw new Exception("在 [ " + obj.getClass().getName() + " ] 的" + propName + "属性上注入值错误！");
		}
	}
	
	/**
	 * 获取指定对象上的指定属性的值
	 * @param obj
	 * @param propName
	 * @return Object
	 * @throws BusinessException
	 */
	public static Object getValue(Object obj,String propName)throws Exception{
		Object value = null;
		try {
			Method getMethod = null;
			try {
				getMethod = obj.getClass().getMethod
				("get" + JOXManager.fstCharUpperCase(propName));
			} catch (Exception e) {
				getMethod = obj.getClass().getMethod
				("is" + JOXManager.fstCharUpperCase(propName));
			}
			value = getMethod.invoke(obj);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("在 [ " + obj.getClass().getName() + " ] 的" + propName + "属性上取出值错误！");
		}
		return value;
	}
	
}
